package com.shop.servlet.client;

import com.shop.entity.User;
import com.shop.service.UserService;
import com.shop.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UserServlet",urlPatterns = "/UserServlet")
public class UserServlet extends HttpServlet {

    UserService service = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取请求的类型
//        UserService service = new UserServiceImpl();
        String action = request.getParameter("action");
        switch (action){
            case "login":
                login(request, response);
                break;
            case "regist":
                regist(request, response);
                break;
            case "quit":
                quit(request, response);
                break;
        }
    }
    //登入
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //账号，密码
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        //调用方法
        User user =service.findUserByAccount(account);
        //页面跳转
        String msg = "";
        if(user == null){
            msg = "账号不存在";
        }else if (!user.getPassword().equals(password)){
            msg = "密码不正确";
        }else {
            msg = "ok";
            request.getSession().setAttribute("loginUser",user);
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //响应
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();
    }
    //退出
    public void quit(HttpServletRequest request,HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("loginUser");
        response.sendRedirect("/client/Login.jsp");
    }
    //注册
    public void regist(HttpServletRequest request, HttpServletResponse response){

    }
}
